from operator import methodcaller
import re
from flask import Blueprint, request, jsonify
from conf.comm import sqlalchemy_context
from database import *
import json
from werkzeug.security import generate_password_hash,check_password_hash
from utils.rediscon import r
from utils.comm import send_message
from utils.myjwt import myjwt
import random
import time
import os
import uuid
from utils.myupyun import myupyun
# 蓝图初始化
bp_users = Blueprint('users', __name__)


# 注册功能实现
@bp_users.route('/reg',methods=['POST'])
@sqlalchemy_context()
def reg():
    if request.method == 'POST':
        gain = request.data
        if not gain:
            gain = request.data
        else:
            gain = json.loads(gain)
        res = re.match('^1[3-9]\d{9}$',gain['mobile'])
        if not res:
                return jsonify({'code':10010})
        user = User(username=gain['username'],
            password=generate_password_hash(gain['password']), mobile=gain['mobile'])
        db.session.add(user)
        db.session.commit()
        return jsonify({'code': 200})

# 获取验证码
@bp_users.route('/gain',methods=['POST'])
@sqlalchemy_context()
def reg_gain():
    data = request.data
    if not data:
        data = request.form
    else:
        data = json.loads(data)
    if not data:
        return jsonify({'code':10012,'matter':'请输入手机号'})
    else:
        res = re.match('^1[3-9]\d{9}$',data['mobile'])
        if not res:
            return jsonify({'code':10010,'matter':'手机号不正确'})
    value = r.get_str(data['mobile'])
    if not value:
        code = str(random.randint(100000,999999))
        res = send_message(data['mobile'],code,1)
        if res:
            r.set_str(data['mobile'],code,60)
            return jsonify({'code':200,'matter':code})
        else:
            return jsonify({'code':10014,'matter':'发送失败'})

    else:
        return jsonify({'code':10013,'matter':'请于30s后再次获取'})

# 手机号登录接口
@bp_users.route('/login2',methods=['POST'])
@sqlalchemy_context()
def login_mobile():
    data = json.loads(request.data)
    user = User.query.filter_by(username=data['mobile']).first()
    if not user:
        num = random.randint(1000,9999)
        str1 = '用户'+str(num)+str(data['mobile'])
        aadmin = User(username=str1,password=generate_password_hash('123'),mobile=data['mobile'])
        db.session.add(aadmin)
        db.session.commit()
        r.del_str(data['mobile'])
        return jsonify({'code':200,'userid':aadmin.id})
    else:
        gain = r.get_str(data['mobile'])
        if data['code']==gain:
            r.del_str(data['mobile'])
            return jsonify({'code':200,'userid':user.id})
        else:
            return jsonify({'code':10017,'matter':'验证码错误'})

# 用户登录接口
list1 = []
@bp_users.route('/login1',methods=['POST'])
@sqlalchemy_context()
def login_user():
    data = json.loads(request.data)
    user = User.query.filter_by(username=data['username']).first()
    if user:
        if check_password_hash(user.password,data['password']):
            token = myjwt.jwt_encode({'data':{'username':data['username'],'password':data['password']}})
            list1.append(token)
            return jsonify({'code':200,'username':user.username,'userid':user.id,'token':token})
        else:
            record = Record.query.filter_by(username=data['username']).first()
            if not record:
                record = Record(username=data['username'],count=1)
                db.session.add(record)
                db.session.commit()
            else:
                date1 = time.strftime('%Y-%m-%d')
                date2 = record.starttime.strftime('%Y-%m-%d')
                if record.count<3:
                    Record.query.filter_by(username=data['username']).update({'count':record.count+1})
                    db.session.commit()
                else:
                    if date1 == date2:
                        return jsonify({"code":10018,'matter':'今日登录次数已达上限'})
                    else:
                        Record.query.filter_by(username=data['username']).delete()
                        record = Record(username=data['username'],count=1)
                        db.session.add(record)
                        db.session.commit()
            return jsonify({'code':10015,'matter':'密码错误'})
    else:
        return jsonify({'code':10016,'matter':'账号错误'})

#返回用户信息接口
@bp_users.route('/getuserinfo')
def getuserinfo():
    #数据库查询返回
    id = request.args.get('userid')
    user = User.query.filter_by(id=id).first()
    dict = {}
    dict['id'] = user.id
    dict['username'] = user.username
    dict['mobile'] = user.mobile
    return jsonify({'code':200,'user':dict})

# 在执行接口前调用
@bp_users.before_request
def before_request():
    #定义一个白名单，把不需要token认证的接口放到列表里
    list=['/users/login2','/users/reg','/users/gain','/users/login1','users/upload']
    if request.path not in list:
        #获取token
        try:
            token = str(request.headers['token'])
        except:
            return jsonify({"code":403,'matter':'请传递token'})
        #解密重新对比token
        newtoken = list1[0]
        if newtoken and myjwt.check(token,newtoken):
            pass
        else:
            return jsonify({"code":403,'matter':'token错误'})

# 上传文件接口
@bp_users.route('/upload',methods=['POST'])
def upload():
    #获取文件
    file = request.files['file']
    #上传到upload文件夹
    #解决文件名被覆盖的问题
    #1.文件重命名   文件名.后缀  1.jpg   asfasfsdf.jpg
    #获取文件后缀
    filetext = os.path.splitext(file.filename)[1]
    newfile = uuid.uuid4().hex+filetext
    #2.在upload下面建立一个文件夹，专业存，文件夹的名字为userid
    userid = request.form.get('userid')
    #根据userid创建文件夹
    #判断此用户文件夹是否存在，存在直接写文件，不存在创建
    path = './static/upload/'+str(userid)
    #不存在创建文件
    if not os.path.exists(path):
        os.mkdir(path)
    file.save(os.path.join(path,newfile))
    return jsonify({"code":200,'filename':newfile})


# @bp_users.route('/goods',methods = ["POST","GET","DELETE"])
# def goods():
#     if request.method == 'POST':
#         gain = request.data
#         if not gain:
#             gain = request.form
#         else:
#             gain = json.loads(gain)
#         user = Goods(name=gain['name'],price=gain['price'],img=gain['img'])
#         db.session.add(user)
#         db.session.commit()
#         return jsonify({'code':200})
#     elif request.method == 'GET':
#         gain = Goods.query.all()
#         list = []
#         for i in gain:
#             dict = {}
#             dict['id'] = i.id
#             dict['name'] = i.name
#             dict['price'] = i.price
#             dict['img'] = i.img
#             list.append(dict)
#         return jsonify({'code':200,'matter':list})
#     else:
#         userid = request.args.get('userid')
#         print("************")
#         print(userid)
#         Goods.query.filter_by(id=userid).delete()
#         db.session.commit()
#         return jsonify({'code':200})
